import { WEBSOCKETS, toSuccess, useEntityManager } from '@sker/core'
import { AutoDeviceWork } from '@sker/entities'
import dayjs from 'dayjs'
import { useData } from '@sker/runtime'
import { z } from 'zod'
import { container } from 'tsyringe'
import { In } from 'typeorm'
export default async () => {
    const input = z.object({
        uuid: z.string()
    });
    const body = input.parse(useData())
    const res = await useEntityManager(async m => {
        const date = dayjs().format('YYYY-MM-DD')
        const res = await m.findOne(AutoDeviceWork, {
            where: {
                uuid: body.uuid,
                date: date,
            }
        })
        if (!res) {
            const res = m.create(AutoDeviceWork, {
                room: 0,
                red: 0,
                money: 0,
                success: 0,
                fail: 0,
                mood: 100,
                continuous_fail: 0,
                continuous_success: 0,
                pre: `unknown`,
                date: date,
                uuid: body.uuid,
                continuous_room_fail: 0,
                continuous_room_success: 0,
                status: `0`,
                type: 'leader'
            })
            await m.save(AutoDeviceWork, res);
            (res as any).isLeader = true;
            return res;
        }
        // 判断是否leader
        // if (res.mood < 100) {
        //     res.type = 'leader';
        // }
        // 判断是否最后10名
        // const websockets = container.resolve(WEBSOCKETS)
        // let ids = [...websockets.keys()];
        // const last10 = await m.find(AutoDeviceWork, { select: { uuid: true }, where: { uuid: In(ids) }, order: { mood: 'asc' }, take: 20 })
        // if (last10.length > 0) {
        //     res.type = last10.map(it => it.uuid).includes(res.uuid) ? 'leader' : 'worker'
        // }
        await m.update(AutoDeviceWork, res.id, { status: `0` })
        return res;
    })
    return toSuccess(res)
}
